const http=require('http');
const https=require('https');
const url = require('url');
const qs=require('querystring');
const fs=require('fs');

const boundaryKey='----------'+randomChar();

const fileName='testUp.css';

const fileData={
    Filename:fileName,
    Upload:'Submit Query',
};

fs.readFile(fileName,'base64',function (err,data) {
    let payload='';
    for (const key in fileData){
        payload+='--' + boundaryKey + '\r\n' + 'Content-Disposition:form-data; name='+key+'; \r\n\r\n';
        payload+=fileData[key]+'\r\n';
    }
    payload += '--' + boundaryKey + '\r\n' + 'Content-Disposition:form-data; name="filedata"; filename='+fileName+'\r\n' + 'Content-Type:application/octet-stream\r\n\r\n';
    payload += data;
    payload += '\r\n--' + boundaryKey + '--';

    console.log(payload);

    //process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

    const options={
        hostname:'admin.house.ifeng.com',
        path:'/pic/tool/upload',
        method: 'post',
        headers:{
            'Content-Type':'multipart/form-data; boundary=' + boundaryKey,
            'Connection':'keep-alive',
            'Content-Length':Buffer.byteLength(payload,'utf8'),
            'Cookie':'TEMP_USER_ID=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiI1YWYxMDFhN2E1OWRiIiwidGltZSI6MTUyNTc0NDAzOX0.BgRmHIZ8nB2CAYkUr7fffuMa_sfdJOu4q3FMKFh0i-g; userid=1525744041296_5lj4235372; vjuids=241d659e.1633d836205.0.37c472c891dd3; IF_REAL=0; vjlast=1525745411.1526450019.11; Hm_lvt_7de106b908198901a1745cbc1021c5e7=1527838649; Hm_lvt_2618c9646a4a7be2e5f93653be3d5429=1527667176,1528886230,1529056363,1529483654; ifh_site=27921%2Ctj; city_redirected=5; sid=96D6CB1BED73CC9F9DFDFC9509188F42user60116096; IF_TIME=1529890631241; IF_USER=kegang%40ifeng.com; ifh_auth=101467_f9b643e72fef42de6fffe4a30386f3ca'
        }
    };

    var req = http.request(options, function (res) {
        console.log('STATUS: ' + res.statusCode);
        //console.log('HEADERS' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('body:' + chunk);
        });

    });

    req.on('error', function(e) {
        console.error("error:"+e);
    });
    req.write(payload);
    req.end();

});

function randomChar() {
    let output='';
    const char='QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789';
    for(let i=0;i<30;i++){
        output+=char[Math.floor(Math.random() * char.length)];
    }
    return output;
}